﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using MicropleSoft.Controls.DialogBox;
using MicropleSoft.WmsApp.Library.ServiceFacade;

namespace MicropleSoft.Controls.ComplexControl
{
    public partial class FormCDialogLookUpEdit : DevExpress.XtraEditors.XtraForm
    {
        private string _memberValueField = string.Empty;
       
        public FormCDialogLookUpEdit()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            foreach (var lookUpViewHeader in LookUpViewHeaders)
            {
                var  gridColumn = new GridColumn();
                gridColumn.FieldName = lookUpViewHeader.Field;
                gridColumn.Width = lookUpViewHeader.Width;
                gridColumn.Caption = lookUpViewHeader.Caption;
                gridColumn.OptionsColumn.AllowEdit = false;
                gridColumn.OptionsColumn.ReadOnly = true;
                if(lookUpViewHeader.IsVisual)
                {
                    _memberValueField = lookUpViewHeader.Field;
                }
                this.gridViewMain.Columns.Add(gridColumn);
            }
            this.xGridControlMain.DataSource = DataSource;
        }

        public Object ResultValue { get; private set; }

        public Object DataSource { get; set; }

        public List<LookUpViewHeader> LookUpViewHeaders { get; set; }

        private void SetResultValue()
        {
            var selectRow = this.gridViewMain.GetRow(this.gridViewMain.FocusedRowHandle);
            if (selectRow != null)
            {
                PropertyInfo propertyInfo = selectRow.GetType().GetProperty(_memberValueField);
                if(propertyInfo != null)
                {
                    this.ResultValue = propertyInfo.GetValue(selectRow, null);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    CustomMessageBox.ShowError("LookUpViewHeaders中不存在IsValueMember=True的项！");
                }
            }
        }

        private void GridView1DoubleClick(object sender, EventArgs e)
        {
            SetResultValue();
        }

        private void GridView1KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode== Keys.Enter)
            {
                SetResultValue();
            }
        }
    }
}